const app = getApp()
const api = require('../../utils/api.js')
const mockData = require('../../utils/data.js')

const DEFAULT_AVATAR = 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=100&h=100&fit=crop'
const USE_MOCK = false

function normalizeReview(item = {}) {
  const images = []
  if (item.images) {
    if (Array.isArray(item.images)) {
      images.push(...item.images.filter(Boolean))
    } else if (typeof item.images === 'string') {
      images.push(...item.images.split(',').map(i => i.trim()).filter(Boolean))
    }
  }

  const reviewTime = item.reviewTime || item.createTime || item.date || ''
  let displayDate = item.date || ''
  let timestamp = Date.now()
  if (reviewTime) {
    const dateObj = new Date(reviewTime)
    if (!isNaN(dateObj.getTime())) {
      timestamp = dateObj.getTime()
      const month = dateObj.getMonth() + 1
      const day = dateObj.getDate()
      displayDate = `${month}月${day}日`
    }
  }

  return {
    id: item.reviewId || item.id || timestamp,
    user: item.userName || item.user || '匿名用户',
    avatar: item.userAvatar || item.avatar || DEFAULT_AVATAR,
    rating: Number(item.rating || 5),
    content: item.content || '',
    images,
    date: displayDate,
    timestamp
  }
}

Page({
  data: {
    productId: null,
    reviews: [],
    filteredReviews: [],
    currentFilter: 'all',
    totalCount: 0,
    imageReviewCount: 0,
    showAddForm: false,
    submitting: false,
    uploading: false,
    newReview: {
      rating: 5,
      content: '',
      images: []
    }
  },
  
  onLoad(options) {
    const productId = parseInt(options.productId, 10)
    if (!productId) {
      wx.showToast({
        title: '未获取到产品信息',
        icon: 'none'
      })
    }
    this.setData({ productId: productId || null })
    this.loadReviews()
  },
  
  loadReviews() {
    if (!this.data.productId && !USE_MOCK) {
      this.useMockReviews()
      return
    }

    if (USE_MOCK) {
      this.useMockReviews()
      return
    }

    api.getProductReviews(this.data.productId)
      .then(list => {
        const normalized = (list || []).map(normalizeReview)
        this.updateReviewState(normalized)
      })
      .catch(err => {
        console.error('加载评价失败:', err)
        this.useMockReviews()
      })
  },

  useMockReviews() {
    const fallback = (mockData.reviews || []).map(normalizeReview)
    this.updateReviewState(fallback)
  },

  updateReviewState(reviews = []) {
    const imageReviewCount = reviews.filter(item => item.images.length > 0).length
    this.setData({
      reviews,
      totalCount: reviews.length,
      imageReviewCount
    }, () => {
      this.applyFilter(this.data.currentFilter)
    })
  },
  
  switchFilter(e) {
    const filter = e.currentTarget.dataset.filter
    this.applyFilter(filter)
    this.setData({
      currentFilter: filter
    })
  },

  applyFilter(filter = 'all') {
    let filtered = [...this.data.reviews]
    if (filter === 'withImage') {
      filtered = filtered.filter(item => item.images.length > 0)
    } else if (filter === 'latest') {
      filtered = filtered.sort((a, b) => b.timestamp - a.timestamp)
    }
    this.setData({ filteredReviews: filtered })
  },

  toggleAddForm() {
    this.setData({
      showAddForm: !this.data.showAddForm
    })
  },

  handleContentInput(e) {
    this.setData({
      newReview: {
        ...this.data.newReview,
        content: e.detail.value
      }
    })
  },

  setRating(e) {
    const rating = Number(e.currentTarget.dataset.value || 5)
    this.setData({
      newReview: {
        ...this.data.newReview,
        rating
      }
    })
  },

  chooseImages() {
    if (this.data.uploading) {
      return
    }
    const remaining = 6 - this.data.newReview.images.length
    if (remaining <= 0) {
      wx.showToast({
        title: '最多上传6张图片',
        icon: 'none'
      })
      return
    }
    wx.chooseImage({
      count: remaining,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const { tempFilePaths } = res
        if (tempFilePaths && tempFilePaths.length > 0) {
          this.uploadImages(tempFilePaths)
        }
      },
      fail: (err) => {
        console.error('选择图片失败', err)
      }
    })
  },

  uploadImages(files = []) {
    if (!files.length) {
      return
    }
    this.setData({ uploading: true })
    wx.showLoading({
      title: '上传中...',
      mask: true
    })
    Promise.all(files.map(path => api.uploadImage(path)))
      .then(urls => {
        this.setData({
          newReview: {
            ...this.data.newReview,
            images: [...this.data.newReview.images, ...urls]
          }
        })
      })
      .catch(err => {
        console.error('上传图片失败', err)
        wx.showToast({
          title: '上传图片失败',
          icon: 'none'
        })
      })
      .finally(() => {
        this.setData({ uploading: false })
        wx.hideLoading()
      })
  },

  removeImage(e) {
    const index = e.currentTarget.dataset.index
    const images = [...this.data.newReview.images]
    images.splice(index, 1)
    this.setData({
      newReview: {
        ...this.data.newReview,
        images
      }
    })
  },

  previewImage(e) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      current: url,
      urls: this.data.newReview.images
    })
  },

  submitReview() {
    if (this.data.submitting || this.data.uploading) {
      return
    }
    if (!this.data.productId) {
      wx.showToast({
        title: '缺少产品信息',
        icon: 'none'
      })
      return
    }
    const content = (this.data.newReview.content || '').trim()
    if (!content) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      })
      return
    }
    const userInfo = this.getCurrentUserInfo()
    const payload = {
      productId: this.data.productId,
      rating: this.data.newReview.rating,
      content,
      images: this.data.newReview.images.join(','),
      userId: userInfo.userId,
      userName: userInfo.nickname || userInfo.userName || '匿名用户',
      userAvatar: userInfo.avatar || DEFAULT_AVATAR
    }
    this.setData({ submitting: true })
    api.createReview(payload)
      .then(() => {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        })
        this.setData({
          newReview: {
            rating: 5,
            content: '',
            images: []
          },
          showAddForm: false
        })
        this.loadReviews()
      })
      .catch(err => {
        console.error('提交评价失败:', err)
        wx.showToast({
          title: err.message || '提交失败',
          icon: 'none'
        })
      })
      .finally(() => {
        this.setData({ submitting: false })
      })
  },

  getCurrentUserInfo() {
    const stored = wx.getStorageSync('userInfo') || {}
    const globalInfo = app.globalData.userInfo || {}
    const userInfo = { ...stored, ...globalInfo }
    if (!userInfo.userId) {
      let tempId = wx.getStorageSync('tempUserId')
      if (!tempId) {
        tempId = Date.now()
        wx.setStorageSync('tempUserId', tempId)
      }
      userInfo.userId = tempId
    }
    if (!userInfo.nickname && userInfo.realName) {
      userInfo.nickname = userInfo.realName
    }
    if (!userInfo.avatar) {
      userInfo.avatar = DEFAULT_AVATAR
    }
    return userInfo
  }
})

